﻿package com.cw.war.ui
{
	import com.cw.utils.WarUtils;
	import com.cw.war.model.core.transaction.Transaction;

	import flash.events.Event;
	import flash.text.TextField;

	/**
	 * 事务处理显示器。对象负责显示一个跑秒的过程
	 * @author DanielLu
	 */
	public class TickerViewer
	{
		/**
		 * 创建事务处理显示器。
		 * @param tf			要显示事务运行的显示器
		 * @param onCompleted	当事务执行结束后的侦听器
		 * @return				事务处理显示器。
		 */
		public static function create ( tf : TextField , transaction : Transaction , onCompleted : Function = null ) : TickerViewer
		{
			return new TickerViewer ( tf , transaction , onCompleted );
		}

		private var tf : TextField;
		private var transaction : Transaction;
		private var onCompleted : Function;

		/**
		 * 创建一个跑秒显示器
		 * @param tf			显示跑秒的文本框
		 * @param transaction	正在执行的事务对象
		 * @param onCompleted	当事务执行完成后的侦听器
		 */
		public function TickerViewer ( tf : TextField , transaction : Transaction , onCompleted : Function = null )
		{
			this.tf = tf;
			this.transaction = transaction;
			this.onCompleted = onCompleted;

			this.transaction.addTickerListener ( this.__onTicker );
			this.transaction.addStopListener ( this.__onTransactionCompleted );
			this.transaction.addCompletedListener ( this.__onTransactionCompleted );
			this.tf.addEventListener ( Event.REMOVED_FROM_STAGE , this.__onTransactionCompleted );
			this.tf.text = WarUtils.formatTime ( this.transaction.getRemainTime () / 1000 );
			// GC.addMonitor( this.tf );
			// GC.addMonitor( this.transaction );
		}

		private function __onTicker ( e : Event ) : void
		{
			this.tf.text = WarUtils.formatTime ( this.transaction.getRemainTime () / 1000 );
		}

		private function __onTransactionCompleted ( e : Event = null ) : void
		{
			if(this.transaction)
			{
				this.transaction.removeTickerListener ( this.__onTicker );
				this.transaction.removeStopListener ( this.__onTransactionCompleted );
				this.transaction.removeCompletedListener ( this.__onTransactionCompleted );
			}
			if(this.tf)
			{
				this.tf.removeEventListener ( Event.REMOVED_FROM_STAGE , this.__onTransactionCompleted );
				//
				this.tf = null;
			}
			this.transaction = null;
			if(this.onCompleted != null)
			{
				this.onCompleted ();
			}
			this.onCompleted = null;
		}

		public function destroy () : void
		{
			this.__onTransactionCompleted ();
		}
	}
}
